package com.NHL.single
{
	import com.NHL.interfaces.IDrag;
	import com.NHL.modules.core.BasicContainer;
	
	import flash.display.DisplayObject;
	import flash.display.Stage;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	public class DragManager
	{
		private static var _inst:DragManager;
		private var _stage:Stage;
		private var _image:DisplayObject;
		private var _prevPoint:Point;
		private var _offsetX:Number;
		private var _offsetY:Number;
		private var _dragStart:IDrag;
		private var _container:BasicContainer;
		private var _prevAccept:IDrag;
		
		public function get container():BasicContainer
		{
			return _container;
		}
		
		public function set container(value:BasicContainer):void
		{
			_container = value;
		}
		
		public static function getInstance():DragManager
		{
			return _inst||(_inst = new DragManager())
		}
		public function DragManager()
		{
			this._stage = GlobalModel.getInstance().stage;
		}
		
		
		
		public  function startDrag(dragClient:IDrag,image:DisplayObject):void
		{
			_prevPoint = new Point(_stage.mouseX,_stage.mouseY);
			_dragStart = dragClient;
			removeImage();
			this._image = image;
			_offsetX = _image.width/2;
			_offsetY = _image.height/2
			_container.addChild(_image);
			GlobalModel.getInstance().stage.addEventListener(MouseEvent.MOUSE_MOVE,onDragMove,false,0,true);
			GlobalModel.getInstance().stage.addEventListener(MouseEvent.MOUSE_UP,onDragUp,false,0,true);
		}
		
		private function onDragMove(evt:MouseEvent):void
		{
			var newPoint:Point = new Point(_stage.mouseX,_stage.mouseY);
			_image.x = _stage.mouseX - _offsetX;
			_image.y = _stage.mouseY - _offsetY;
			var point:Point = new Point(_stage.mouseX,_stage.mouseY);
			var arr:Array = _stage.getObjectsUnderPoint(point);
			var accept:IDrag = null;
			for(var i:int = arr.length - 1;i > -1;--i)
			{
				if(arr[i].parent is IDrag)
				{
					
					if((arr[i].parent as IDrag).type = _dragStart.type)
					{
						accept = arr[i].parent as IDrag;
						if(accept != _prevAccept)
						{
							if(_prevAccept)
							{
								_prevAccept.dragOut();
							}
							_prevAccept = accept;
							_prevAccept.dragIn();
						}
						break;
					}
				}
			}
			
		}
		
		private function removeImage():void
		{
			if(_image&&_container.getChildIndex(_image) > -1)
			{
				_container.removeChild(_image);
			}
		}
		
		private function onDragUp(evt:MouseEvent):void
		{
			_stage.removeEventListener(MouseEvent.MOUSE_MOVE,onDragMove);
			_stage.removeEventListener(MouseEvent.MOUSE_UP,onDragUp);
			if(_prevAccept.accept(_dragStart))
			{
				removeImage();
			}
			else
			{
				var point:Point = _dragStart.localToGlobal(new Point(0,0));
				Tweenlite.to(_image,0.5,{x:point.x,y:point.y,alpha:0.1,onComplete:removeImage()})
			}
		}
	}
}